// ActionScript file
import Components.TitleWindow.twSaveCustomerAlert;
import Components.TitleWindow.twVehicleTree;

import flash.events.Event;

import mx.controls.Alert;
import mx.events.CloseEvent;
import mx.managers.PopUpManager;

import org.flexlancer.Logger.Logger;
import org.flexlancer.databases.Alerts;
import org.flexlancer.databases.Customers;
import org.flexlancer.databases.dbSalesInvoice;
import org.flexlancer.enums.EmbedResources;
import org.flexlancer.events.SelectedFromListEvent;
import org.flexlancer.utils.GenericUtils;

private var custName:String;
private var custType:String;
[Bindable]
private var dpCustomerType:Array;
[Bindable]
private var custInfo:Array = new Array();
[Bindable]
private var vehicleInfo:Array = new Array();
[Bindable]
private var alertInfo:Array = new Array();
[Bindable]
private var billInfo:Array = new Array();

private function init():void{
	try{
		this.dpCustomerType = EmbedResources.CUSTOMER_TYPES;
		if ( this.editObject != null ){
			this.txtCustomerName.text = this.editObject.customername;
			this.txtLoyaltyID.text = this.editObject.customerloyalty;
			this.cmbCustomerType.selectedItem = this.editObject.customertype;
			
			for each ( var singleContact:Object in this.editObject.contactdetails ){
				var insertObj:Object = new Object();
				insertObj.type = singleContact.contacttype;
				insertObj.detail = singleContact.contactdetail;
				this.custInfo.push(insertObj);
			}
			this.dgContactsInfo.dataProvider = this.custInfo;
			
			for each ( var singleVehicle:Object in this.editObject.vehicledetails ){
				var insertVeh:Object = new Object();
				insertVeh.type = singleVehicle.vehicletype;
				insertVeh.detail = singleVehicle.vehicledetail;
				insertVeh.regnum = singleVehicle.regnum;
				this.vehicleInfo.push(insertVeh);
			}
			this.dgVehicleInfo.dataProvider = this.vehicleInfo;
			this.RefreshAlerts();
			
			this.billInfo = dbSalesInvoice.List("refcustomer = "+this.editObject.customerid);
			var totalrec:Number = 0;
			
			for each ( var singleBill:Object in this.billInfo ){
				if ( singleBill.balance < 0 ) singleBill.billbalance = singleBill.balance;
				else singleBill.billbalance = 0;
				totalrec += singleBill.billbalance;
				singleBill.billdate = GenericUtils.DateObject(singleBill.salesdate);
			}
			totalrec = -totalrec;
			this.lblTotalRecieables.text = totalrec.toString();
		}else{
			this.currentState = "Add";
		}		
	}catch(err:Error){
		Logger.LogE(err);
	}
}
/*
private function DateObject(val:String):Date{
	try{
		var toks:Array = val.split("-");
		return new Date(Number(toks[0]),Number(toks[1]),Number(toks[2]));
	}catch(err:Error){
		throw err;
	}
	return new Date();
}
*/
private function RefreshAlerts():void{
	try{
		this.alertInfo = new Array();
		for each ( var singleAlert:Object in Alerts.List("refid LIKE 'CUST-"+this.editObject.customerid+"'") ){
			var insertAlr:Object = new Object();
			insertAlr.alertid = singleAlert.alertid;
			insertAlr.alerttype = singleAlert.alerttype;
			insertAlr.alertaction = singleAlert.alertaction;
			insertAlr.isactive = singleAlert.isactive;
			insertAlr.alertdate = GenericUtils.DateObject(singleAlert.alertdate).toDateString();
			switch(insertAlr.isactive){
				case 0:
					insertAlr.alertstatus = "DISABLE";
				break;
				case 1:
					insertAlr.alertstatus = "ACTIVE";
				break;
				default:
					insertAlr.alertstatus = "UNKNOWN";
				break;
			}
			this.alertInfo.push(insertAlr);
		}
		this.dgAlert.dataProvider = this.alertInfo;
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function PerformDeleteContact():void{
	try{
		if ( this.dgContactsInfo.selectedItem != null ){
			var index:Number = this.custInfo.indexOf(this.dgContactsInfo.selectedItem);
			this.custInfo.splice(index,1);
			this.dgContactsInfo.dataProvider = this.custInfo;
		}else{
			Alert.show("Please select a contact to delete","No contact selected");
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function PerformDeleteVehicle():void{
	try{
		if ( this.dgVehicleInfo.selectedItem != null ){
			var index:Number = this.vehicleInfo.indexOf(this.dgVehicleInfo.selectedItem);
			this.vehicleInfo.splice(index,1);
			this.dgVehicleInfo.dataProvider = this.vehicleInfo;
		}else{
			Alert.show("Please select a vehicle to delete","No vehicle selected");
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnDeleteContact():void{
	try{
		this.PerformDeleteContact();
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private var editObject:Object;

public function set EditObject(val:Object):void{
	try{
		this.editObject = val;
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function ChooseFromList_OnClick():void{
	try{
		var selectVehicle:twVehicleTree = PopUpManager.createPopUp(this,twVehicleTree,true) as twVehicleTree;
		selectVehicle.addEventListener(SelectedFromListEvent.SELECTED,OnVehicleSelectedFromList);
		PopUpManager.centerPopUp(selectVehicle);
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnVehicleSelectedFromList(evt:SelectedFromListEvent):void{
	try{
		this.txtVehicleInfo.text = evt.Data;
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnAddInfo():void{
	try{
			if ( this.rgContactTypeGroup.selectedValue == null ){
				Alert.show("Contact Info type is not defined","Please select contact info type");
				return;
			}
			var info:Object = new Object();
			info.type = this.rgContactTypeGroup.selectedValue.toString();
			if(this.taContactDetails.text.length > 0){
				info.detail = this.taContactDetails.text;
				this.custInfo.push(info);
			}else	{
				Alert.show("Details are missing!","Field Empty");
			}
			this.dgContactsInfo.dataProvider = this.custInfo;
			this.taContactDetails.text = "";
			this.taContactDetails.setFocus();

			var arrNext:Array = ["Address","Mobile","PTCL","Email","Fax","Other"]; 
			var ind:Number = arrNext.indexOf(this.rgContactTypeGroup.selectedValue);
			ind = (ind + 1) % arrNext.length;
			this.rgContactTypeGroup.selectedValue = arrNext [ ind ];
			//Alert.show(this.custInfo.toString());
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnAddVehicle():void{
	try{
			if ( this.rgVehicleTypeGroup.selectedValue == null ){
				Alert.show("Vehicle type is not defined","Please select Vehicle type");
				return;
			}
			var info:Object = new Object();
			info.type = this.rgVehicleTypeGroup.selectedValue.toString();
			
			if(this.txtVehicleInfo.text.length > 0){
				info.detail = this.txtVehicleInfo.text;				
			}else	{
				Alert.show("Vehicle Info is  missing!","Field Empty");
			}
			
			if(this.txtRegNum.text.length > 0){
				info.regnum = this.txtRegNum.text;				
			}else	{
				Alert.show("Registration Number is missing!","Field Empty");
			}
			if(this.txtVehicleInfo.text.length > 0 && this.txtRegNum.text.length > 0){
				this.vehicleInfo.push(info);
			}
			this.dgVehicleInfo.dataProvider = this.vehicleInfo;
			//Alert.show(this.custInfo.toString());
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnSaveClick():void{
	try{
		if(this.txtCustomerName.text.length<1){
			Alert.show("Name Field is Empty","Empty Field");
			return;
		}else
		{
			this.custName = this.txtCustomerName.text;
		}
		
		if(this.cmbCustomerType.text.length<1){
			Alert.show("Select Customer Type","Type not selected");
			return;
		}else{
			this.custType = this.cmbCustomerType.text; 
		}

		if ( this.editObject == null ){
			Customers.Add(this.custName, this.custType,this.txtLoyaltyID.text , this.custInfo , this.vehicleInfo);
	
			if(this.chkAddAnother.selected){
				this.txtCustomerName.text = "";
				this.custInfo = new Array();
				this.vehicleInfo = new Array();
			}else{
				PopUpManager.removePopUp(this);
			}	
		}else{
			Customers.Update(this.editObject.customerid,this.custName, this.custType,this.txtLoyaltyID.text , this.custInfo , this.vehicleInfo);
			PopUpManager.removePopUp(this);
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}

//------------------------------------------------
//				Alerts Script
//------------------------------------------------

private function OnAddAlert():void{
	try{
		var addAlert:twSaveCustomerAlert = PopUpManager.createPopUp(this,twSaveCustomerAlert,true) as twSaveCustomerAlert;
		addAlert.customerid = this.editObject.customerid;
		addAlert.addEventListener(twSaveCustomerAlert.ALERT_ADDED,OnAlertAdded);
		PopUpManager.centerPopUp(addAlert);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnAlertAdded(evt:Event):void{
	try{
		this.RefreshAlerts();
	}catch(err:Error){
		Logger.LogE(err);
	}
}
private function OnDaleteAlert():void{
	try{
		if ( this.dgAlert.selectedItem == null ){
			Alert.show("Please select any alert to delete.");
			return;
		}
		Alert.show("Are you sure to remove the alert?","Confirmation",Alert.YES|Alert.NO,this,OnDeleteAlertConfirmation);
	}catch(err:Error){
		Logger.LogE(err);
	}
}

private function OnDeleteAlertConfirmation(evt:CloseEvent):void{
	try{
		if (evt.detail == Alert.YES ) {
			Alerts.Delete("alertid = "+this.dgAlert.selectedItem.alertid);
			this.RefreshAlerts();
		}
	}catch(err:Error){
		Logger.LogE(err);
	}
}